package battleship;

public class BattleshipBoard 
{
   public static final int  Bblank = 0;
   public static final int  Bship  = 1;
   public static final int  Bmiss  = 2;
   public static final int  Bhit   = 3;
   
   public static final int  ShipHoriz = 0;
   public static final int  ShipVert = 1;

   private int m_width;
   private int m_height;
   
   private int[][] m_board;
   
   private int m_shipSize;
   private int m_numHits;
   
   public BattleshipBoard(int width, int height)
   {
      m_width  = width;
      m_height = height;

      m_board = new int[m_height][m_width];
      
      for ( int x = 0; x < m_width; x++ )
      {
         for ( int y = 0; y < m_height; y++ )
         {
            m_board[x][y] = Bblank;        
         }
      }
      m_shipSize = 0;
      m_numHits  = 0;

      System.out.println("Board size (HxW): " + height + ", " + width);
   }
   
   //
   // PlaceShip: Places the ship at specified coordinate.
   //
   public boolean placeShip(int x, int y, int direction, int size)
   {
      System.out.println("Ship location: x = " + x + ", y = " + y);                   // Debugging only.
      System.out.println("Direction: " + (direction == ShipHoriz ? "Horz" : "Vert") ); // Debugging only.

      if ( x >= m_width || y >= m_height ) return false;
      
      if ( direction == ShipHoriz ) { 
          if ( x + size > m_width )  
              return false; 
      }
      else {
          if ( y + size > m_height ) 
              return false; 
      }
   
      m_shipSize = size;
      
      for ( int i = 0; i < size; i++ )
      {
         m_board[y][x] = Bship;
         
         System.out.println("Marking Coord: x = " + x + ", y = " + y); // Debugging only.
         
         if ( direction == ShipHoriz ) x++;
         else                              y++;
      }
      
      return true; 
   }
   //
   // shootAtShip: Called to take a shot at the ship on the board. The board will return
   // a status indicating how the shot went.
   //
   public int shootAtShip(int x, int y)
   {
      if ( x >= m_width || y >= m_height ) return -1;
      
      if ( m_board[y][x] == Bhit || m_board[y][x] == Bmiss ) return -2;
      
      if ( m_board[y][x] == Bship ) { m_board[y][x] = Bhit;  m_numHits++;  }
      else                                     { m_board[y][x] = Bmiss;               }   

      return m_board[y][x];
   }
   
   public boolean hasShipBeenSunk()
   {
      return (boolean)(m_numHits == m_shipSize);
   }
   
   public int getWidth()  { 
       return m_width;  
   }
   
   public int getHeight() { 
       return m_height; 
   }
}
